package org.k.vmmock.util;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by hengxianwang on 16-10-29.
 */
public class FileUtils {

    /**
     * 创建文件
     *
     * @param baseFile
     * @param fileName
     */
    public static void createFile(File baseFile, String fileName) throws IOException {
        File file = new File(baseFile, fileName);
        if (!file.exists()) file.createNewFile();
    }

    /**
     * 创建文件夹
     *
     * @param baseFile
     * @param dirName
     * @throws IOException
     */
    public static void createDir(File baseFile, String dirName) throws IOException {
        File file = new File(baseFile, dirName);
        if (!file.exists()) file.mkdir();
    }


    /**
     * copy文件
     *
     * @param src
     * @param target
     * @throws IOException
     */
    public static void copy(String src, String target) throws IOException {
        FileInputStream in = null;
        FileOutputStream out = null;
        FileChannel inc = null;
        FileChannel outc = null;
        try {
            in = new FileInputStream(src);
            out = new FileOutputStream(target);
            inc = in.getChannel();
            outc = out.getChannel();
            ByteBuffer buff = ByteBuffer.allocate(1024 * 100);

            outc.transferFrom(inc, 0, inc.size());
        } finally {
            if (outc != null) outc.close();
            if (inc != null) inc.close();
            if (out != null) out.close();
            if (in != null) in.close();
        }
    }

    /**
     * @param src
     * @param target
     * @throws IOException
     */
    public static void copyJarFile2Local(String src, String target) throws IOException {
        File targetFile = new File(target);
        //System.out.println(src);
        BufferedInputStream fis = new BufferedInputStream(FileUtils.class.getClassLoader().getResourceAsStream(src));
        FileOutputStream fos = new FileOutputStream(targetFile);
        byte[] buf = new byte[1024];
        int c = 0;
        while ((c = fis.read(buf)) != -1) {
            fos.write(buf, 0, c);
        }
        fis.close();
        fos.close();
    }

    public static String readFile2Str(String url) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(url), "utf-8"));
        String data = "";
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            data += inputLine;
        }
        in.close();
        return data.toString();
    }
}
